import os.path
import sys

students = []


def save():
    '''
    用于存档
    :return:
    '''
    with open("record.txt", 'w', encoding='utf8') as f:
        for student in students:
            f.write(f"{student['studentId']}\t{student['name']}\t{student['gender']}\t{student['className']}\n")
        print(f"[存档成功] 共存储了{len(students)}条记录!")


def load():
    '''
    用于读档
    '''
    # 如果存档文件不存在, 则直接跳过读档流程.
    # 为了避免读方式打开文件的时候, 文件不存在引起异常.
    if not os.path.exists("record.txt"):
        return

    global students
    students = []
    with open('record.txt', 'r', encoding='utf8') as f:
        for line in f:
            line = line.strip()
            tokens = line.split('\t')
            if len(tokens) != 4:
                print("当前行数据格式有误! line = {line}")
                continue
            student = {
                'studentId': tokens[0],
                'name': tokens[1],
                'gender': tokens[2],
                'className': tokens[3]
            }
            students.append(student)
        print(f"[读档成功] 共读取了{len(students)}条记录！")


def menu():
    print("1.新增学生信息")
    print("2.显示学生信息")
    print("3.查找学生信息")
    print("4.删除学生信息")
    print("0.退出")
    choice = input("请输入你要进行的操作: ")
    return choice


def insert():
    print("[新增学生] 开始!")
    studentId = input("请输入要新增的学生学号: ")
    name = input("请输入要新增的学生姓名: ")
    gender = input("请输入要新增的学生性别: ")
    while gender not in {"男", "女"}:
        print("输入的性别有误请重新输入")
        gender = input("请输入要新增的学生性别: ")
    className = input("请输入要新增的学生所在班级: ")
    student = {
        'studentId': studentId,
        'name': name,
        'gender': gender,
        'className': className
    }
    global students
    students.append(student)
    save()
    print("[新增学生] 完毕!")


def show():
    print("[显示学生] 开始!")
    for student in students:
        print(f"[{student['studentId']}]\t{student['name']}\t{student['gender']}\t{student['className']}")
    print(f"[显示学生] 结束! 显示了{len(students)}条学生信息")


def find():
    print("[查找学生] 开始!")
    name = input("请输入要查找的学生姓名: ")
    count = 0
    for student in students:
        if name == student['name']:
            print(f"[{student['studentId']}]\t{student['name']}\t{student['gender']}\t{student['className']}")
            count += 1
    print(f"[查找学生] 结束! 一共找到了{count}位学生")


def delete():
    print("[删除学生] 开始!")
    studentId = input("请输入要删除学生的学号: ")
    for student in students:
        if studentId == student['studentId']:
            print(f"删除{student['name']}学生的信息!")
            students.remove(student)
    save()
    print("[删除学生] 结束!")


def main():
    print("------------------------")
    print("----欢迎来到学生管理系统----")
    print("------------------------")
    load()
    while True:
        choice = menu()
        if choice == '0':
            print("goodBye!")
            sys.exit(0)
        elif choice == '1':
            insert()
        elif choice == '2':
            show()
        elif choice == '3':
            find()
        elif choice == '4':
            delete()
        else:
            print("输入格式有误,请重新输入!")


main()



